package com.yylending.las.main.message;

import android.text.TextUtils;

import com.yyfax.common.CLog;
import com.yyfax.infrastructure.eventbus.EventAgent;
import com.yyfax.infrastructure.mvp.IView;
import com.yyfax.infrastructure.mvp.Presenter;
import com.yyfax.infrastructure.mvp.PresenterFactory;
import com.yyfax.infrastructure.network.entity.BaseResultEntity;
import com.yyfax.infrastructure.network.entity.EmptyEntity;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

/**
 * 消息红点展示
 * Created by ying_he on 2017/8/3.<br>
 * Copyright  2017 www.yylending.com. All Rights Reserved.<br><br>
 */
public class MsgStatusPresenter extends Presenter<MsgStatusModel, MsgStatusPresenter.View>{
    private static final String TAG = MsgStatusPresenter.class.getSimpleName();
    private static final int FUNCTION_CODE_MSG_STATUS = 1001;

    private View mView;
    private String mRequestPage;

    public static class Generator implements PresenterFactory<MsgStatusPresenter> {
        @Override
        public MsgStatusPresenter create() {
            return new MsgStatusPresenter();
        }
    }

	public interface View extends IView {
		void getMsgStatusSuccess(int msgCount);
	}

    @Override
    public void attach(MsgStatusPresenter.View view) {
        mRequestPage = view.getClass().getName();
        mView = view;
        mModel = new MsgStatusModel();
        EventAgent.register(this);
    }

    @Override
    public void detach() {
        mView = null;
        mModel = null;
        EventAgent.unregister(this);
    }

    public void getMsgStatus() {
        execute(new EmptyEntity(), FUNCTION_CODE_MSG_STATUS, false, null, mRequestPage);
    }

	@Subscribe(threadMode = ThreadMode.MAIN)
	public void getMsgStatusResult(MsgStatusModel.MsgStatusResult result) {
		if (TextUtils.equals(result.requestPage, mRequestPage)) {
			if (BaseResultEntity.isResponseSuccess(result)) {
				MsgStatusModel.MsgStatus msgStatus = result.getData();
				if (msgStatus != null) {
					String msgCountStr = msgStatus.count;
					if (!TextUtils.isEmpty(msgCountStr)) {
						int msgCount = 0;
						try {
							msgCount = Integer.valueOf(msgCountStr);
						} catch (Exception e) {
							CLog.e(TAG, e.getMessage());
						}

						if (msgCount > 0) {
							mView.getMsgStatusSuccess(msgCount);
						}
					}
				}
			}
		}
	}
}
